package wallpapers.bing.ruzin.bingwallpapers;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by ruzin on 9.2.15.
 */
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    static String wallUrl = "";
    static String copyright = "";

    public String getWallUrlfromJSON (String url, String resolution) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
            while ((line = reader.readLine()) !=null)
            {
                sb.append(line+"\n");
            }
            is.close();
            json = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            jObj = new JSONObject(json);
            JSONArray jsonMainNode = jObj.optJSONArray("images");
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
            copyright = jsonChildNode.getString("copyright");
            wallUrl = "www.bing.com" + jsonChildNode.getString("urlbase") + "_" + resolution + ".jpg" ;
        }
        catch (JSONException j) {
            j.printStackTrace();
        }
        return wallUrl+";"+copyright;
    }
}


